<template>
  <div class="scheduled-task-container">
    <div class="page-header">
      <h2>定时任务执行<span>（{{ taskList.length }}个任务）</span></h2>
      <div class="header-actions">

        <a-button style="margin-left: 8px;" @click="handleRefresh">
          <sync-outlined />
          刷新
        </a-button>
      </div>
    </div>
    
    <div class="table-section">
      <a-card>
        <div class="table-wrapper">
          <Spin :spinning="loading" tip="加载中...">
            <a-table
              :bordered="true"
              :columns="columns"
              :data-source="taskList"
              :pagination="pagination"
              row-key="id"
            >
              <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'triggerStatus'">
                  <a-tag :color="getStatusColor(record.triggerStatus)">
                    {{ getStatusText(record.triggerStatus) }}
                  </a-tag>
                </template>
                <template v-else-if="column.key === 'operation'">
                  <a-button size="small" type="primary" @click="handleExecute(record)">
                    执行
                  </a-button>
                </template>
              </template>
            </a-table>
          </Spin>
        </div>
      </a-card>
    </div>


  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import {
  SyncOutlined
} from '@ant-design/icons-vue';
import { message, Modal, Spin } from 'ant-design-vue';
import xxlJobApi from '../utils/xxlJobApi';

// 表格列配置
const columns = [
  {
    title: '任务ID',
    dataIndex: 'id',
    key: 'id',
    width: 100,
    align: 'center'
  },
  {
    title: '任务名字',
    dataIndex: 'jobDesc',
    key: 'jobDesc',
    align: 'center'
  },
  {
    title: '状态',
    dataIndex: 'triggerStatus',
    key: 'triggerStatus',
    width: 100,
    align: 'center'
  },
  {
    title: '操作',
    key: 'operation',
    fixed: 'right',
    align: 'center',
    width: 100
  }
];

// 任务数据
const taskList = ref<Array<Record<string, any>>>([]);

// 加载状态
const loading = ref(false);

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`
});



// 获取状态文本
const getStatusText = (status: number) => {
  const statusMap: Record<string, string> = {
    '0': '停止',
    '1': '运行中',
    '-1': '停止'
  };
  return statusMap[status.toString()] || '未知';
};

// 获取状态颜色
const getStatusColor = (status: number) => {
  const colorMap: Record<string, string> = {
    '0': 'default',
    '1': 'green',
    '-1': 'default'
  };
  return colorMap[status.toString()] || 'default';
};


// 获取任务列表
const fetchTaskList = async () => {
  loading.value = true;
  try {

    
    // 真实API调用代码（暂时注释）
    
    const response = await xxlJobApi.post(
      '/jobinfo/pageList',
      'jobGroup=5&triggerStatus=-1&jobDesc=处理委案和委案撤案的任务&executorHandler=&author=&start=0&length=100'
    );
    
    if (response.data && response.data.data) {
      taskList.value = response.data.data;
      pagination.total = response.data.recordsTotal || 0;
      message.success('获取任务列表成功');
    } else {
      message.error('获取任务列表失败：数据格式错误');
    }
    
  } catch (error) {
    console.error('获取任务列表失败:', error);
    message.error('获取任务列表失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

// 处理刷新
const handleRefresh = () => {
  fetchTaskList();
};

// 处理执行任务
const handleExecute = (record: any) => {
  Modal.confirm({
    title: '确认执行',
    content: `确定要执行任务"${record.jobDesc}"吗？`,
    okText: '执行',
    cancelText: '取消',
    onOk: async () => {
      try {
        const response = await xxlJobApi.post(
          '/jobinfo/trigger',
          `id=${record.id}`
        );
        
        if (response.data && response.data.code === 200) {
          message.success('任务执行成功');
          // 刷新列表
          fetchTaskList();
        } else {
          message.error('任务执行失败：' + (response.data.msg || '未知错误'));
        }
      } catch (error) {
        console.error('执行任务失败:', error);
        message.error('执行任务失败，请稍后重试');
      }
    }
  });
};

// 初始化加载数据
onMounted(() => {
  fetchTaskList();
});
</script>

<style scoped>
.scheduled-task-container {
  padding: 24px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #1a1a1a;
}

.table-section {
  margin-top: 24px;
}

.table-wrapper {
  overflow-x: auto;
}
</style>
